package com.dpj.servlet.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //判断是否是登录注册页面，如果是直接放行
        String[] urls={"/loginServlet","/registerServlet","/checkCodeServlet","/css/","/imgs/","/login.jsp","/register.jsp"};
        HttpServletRequest req= (HttpServletRequest) request;
        String url = req.getRequestURL().toString();
        for(String u:urls){
            if(url.contains(u)){
                //找到了，放行
                chain.doFilter(request,response);
                return;
            }
        }

        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        //未登录，跳转登录页面
        if(user==null) {
            req.setAttribute("msg", "你当前还没登录，请登录");
            req.getRequestDispatcher("/login.jsp").forward(req, response);

        }else {
            chain.doFilter(req,response);

        }


    }
}
